package huu.phong.googlemusic;

import huu.phong.googlemusic.model.Song;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

public class Album {
	public String title;
	public List<Song> songs;
	public String artist;
	public String albumArt;
	public static final String FOLDER = "Images";
	public String file;
	
	static {
		File file = new File(FOLDER);
		if (!file.exists()){
			file.mkdir();
		}
	}
	
	public Album(String title){
		this.title = title;
		songs = new ArrayList<Song>();
	}
	
	public Album(String title, Collection<Song> songs){
		this.title = title;
		this.songs = (List<Song>) songs;
	}
	
	public int hashCode(){
		return title.hashCode();
	}
	
	public boolean equals(Object obj){
		boolean ret = false;
		if (obj instanceof Album){
			Album album = (Album) obj;
			if (album.title.equals(title)) ret = true;
		}
		return ret;
	}
	
	public String toString(){
		StringBuilder builder = new StringBuilder("<html><h3 style='margin:0; padding: 0;'>" + title + " (" +songs.size() + " songs)" + "</h3>");
		for (int i = 0; i < Math.min(7, songs.size()); i++){
			Song song = songs.get(i);
			builder.append(song.toString() + "<br/>");
		}
		return builder.toString() + "</html>";
	}

	public String getAlbumInfo(){
		StringBuilder builder = new StringBuilder("<html><h3 style='margin:0; padding: 0; text-align:center;'>" + title + " (" +songs.size() + " songs)" + "</h3><hr/>");
		for (int i = 0; i < Math.min(20, songs.size()); i++){
			Song song = songs.get(i);
			builder.append(song.toString() + "<br/>");
		}
		return builder.toString() + "</html>";
	}
	
	public void saveImage(){
		File localAlbumArt = new File(FOLDER + "\\" + title + ".jpg");
		if (localAlbumArt.exists()){
			file = localAlbumArt.getAbsolutePath();
			return;
		}
		try {
			BufferedInputStream in = new BufferedInputStream(new URL(albumArt).openStream());
			BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(localAlbumArt));
			byte[] buffer = new byte[4096];
			int reading = -1;
			while ((reading = in.read(buffer)) != -1){
				out.write(buffer, 0, reading);
			}
			out.flush();
			out.close();
			in.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		file = localAlbumArt.getAbsolutePath();
	}
}
